package com.access.boot.autoconfigure.apisdk.proxy;

import com.access.boot.autoconfigure.apisdk.GlobalConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Objects;

/**
 * @author Yangzhen
 * @date 2022/5/28 15:41
 * @since 1.0.0
 */
@Slf4j
public class AccessorFactoryBean implements FactoryBean<AccessorFactory>, InitializingBean, BeanNameAware, ApplicationContextAware {

    private static ApplicationContext ctx;

    private AccessorFactory accessorFactory;

    private GlobalConfiguration globalConfiguration;

    public AccessorFactoryBean(GlobalConfiguration globalConfiguration) {
        this.globalConfiguration = globalConfiguration;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    }

    @Override
    public AccessorFactory getObject() throws Exception {
        return accessorFactory = new ApiSdkAccessorFactory(globalConfiguration);
    }

    @Override
    public Class<?> getObjectType() {
        return Objects.isNull(accessorFactory) ? AccessorFactory.class : this.accessorFactory.getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void setBeanName(String beanName) {
        AccessorProxyBean.accessFactoryName = beanName;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ctx = applicationContext;
    }
}
